package com.example.newsmanager.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.newsmanager.common.Result;
import com.example.newsmanager.entity.DTO.*;
import com.example.newsmanager.entity.User;
import com.example.newsmanager.service.UserService;
import com.example.newsmanager.util.MailUtil;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeUtility;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,Object> template;

    @Autowired
    private JavaMailSender mailSender;

    @PostMapping("/login")
    public Result<Map<String,String>> userLogin(@RequestBody @Valid LoginDTO loginDTO){
        String token = userService.userLogin(loginDTO);
        if(token != null){
            Map<String,String> data = new HashMap<>();
            data.put("token",token);
            return Result.success(data);
        }
        return Result.fail(202,"用户名或密码错误");
    }

    @PostMapping("/login_admin")
    public Result<Map<String,String>> adminLogin(@RequestBody @Valid LoginDTO loginDTO){
        String token = userService.adminLogin(loginDTO);
        if(token != null){
            Map<String,String> data = new HashMap<>();
            data.put("token",token);
            return Result.success(data);
        }
        return Result.fail(202,"登录信息错误或无权限");
    }

    @PostMapping("/logout")
    public Result<Map<String,String>> logout(HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        String key = "user"+currentUser.getUserId();
        template.delete(key);
        return Result.success("退出登录成功");
    }

    @GetMapping(value = "/getCode",params = "email")
    public Result<Map<String,Object>> sendEmail(@RequestParam String email) throws UnsupportedEncodingException, AddressException {
        String key = "msg_"+email;
        String already_have = (String) template.opsForValue().get(key);
        if(already_have == null){
            // 随机生成一个6位数字型的字符串
            String code = MailUtil.generateRandom4DigitCode();
            // 邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("天下新闻邮箱验证码");
            message.setText("尊敬的: "+email+"您的校验验证码为: "+code+",有效期2分钟，请不要把验证码信息泄露给其他人,如非本人请勿操作");
            message.setTo(email);
            // 对方看到的发送人
            message.setFrom(new InternetAddress(MimeUtility.encodeText("理塘丁真")+"<2456138706@qq.com>").toString());
            //发送邮件
            try {
                mailSender.send(message);
                template.opsForValue().set(key,code,2,TimeUnit.MINUTES);
                log.info("邮件发送成功");
                return Result.success();
            }catch (Exception e){
                log.error("邮件发送出现异常");
                log.error("异常信息为"+e.getMessage());
                log.error("异常堆栈信息为-->");
                e.printStackTrace();
                return Result.fail("验证码发送失败");
            }
        }
        return Result.fail("验证码已发送");
    }

    @PostMapping("/register")
    public Result<Map<String, Object>> userRegister(@RequestBody @Valid RegisterDTO registerDTO){
        Map<String, Object> data = userService.userRegister(registerDTO);
        if(data != null){
            return Result.success(data);
        }
        return Result.fail(202,"该用户已被注册或验证码错误");
    }

    @GetMapping(value = "/list",params = "pages")
    public Result<Map<String,Object>> getAllUser(@RequestParam Integer pages){
        Page<User> page = new Page<>(pages, 6);
        userService.page(page,null);
        Map<String,Object> data = new HashMap<>();
        List<User> userList = page.getRecords();
        if(userList != null){
            data.put("totals",page.getTotal());
            data.put("currentPages",page.getCurrent());
            data.put("pageNumber",page.getPages());
            data.put("rows",userList);
            return Result.success(data);
        }
        return Result.fail(100,"获取用户失败");
    }
    @GetMapping("/my_info")
    public Result<Map<String,Object>> getUserDetail(HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        Map<String,Object> data = userService.getUserDetail(currentUser.getUserId());
        return Result.success(data);
    }

    @DeleteMapping(value = "/delete",params = "userId")
    public Result<Map<String,Object>> deleteUser(@RequestParam String userId){
        boolean isDelete = userService.removeById(userId);
        if(isDelete){
            return Result.success("删除成功");
        }
        else {
            return Result.fail("删除失败");
        }
    }

    @PutMapping("/update_auth")
    public Result<Map<String,Object>> updateUserAuth(@RequestBody @Valid UpdateAuthDTO updateAuthDTO,HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        if(currentUser.getUserType() == 3){
            if(currentUser.getUserId().equals(updateAuthDTO.getUserId())){
                return Result.fail(403,"无权修改当前用户权限");
            }
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            boolean isUpdate = userService.update(updateWrapper.eq("user_id",updateAuthDTO.getUserId())
                    .set("user_type",updateAuthDTO.getUserType()));
            if(isUpdate){
                return Result.success("更新用户权限成功");
            }
            else {
                return Result.fail("更新用户权限失败");
            }
        }
        return Result.fail(403,"无更改权限");
    }

    @PutMapping("/update_password")
    public Result<Map<String,Object>> updateUserPassword(@RequestBody @Valid UpdatePassword updatePassword,HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        String key = "msg_"+updatePassword.getEmail();
        String code = (String) template.opsForValue().get(key);
        if(updatePassword.getCode().equals(code)){
            template.delete(key);
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            boolean isUpdate = userService.update(updateWrapper.eq("user_id",currentUser.getUserId())
                    .set("password",updatePassword.getPassword()));
            if(isUpdate){
                return Result.success("修改密码成功");
            }
            else {
                return Result.fail(100,"修改密码失败");
            }
        }
        return Result.fail(700,"验证码错误");
    }

    @PutMapping("/update")
    public Result<Map<String,Object>> updateUser(@RequestBody @Valid UpdateUserDTO updateUserDTO,HttpServletRequest request){
        User currentUser = (User) request.getAttribute("currentUser");
        if(currentUser == null){
            return Result.fail("登录状态失效");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        boolean isUpdate = userService.update(updateWrapper.eq("user_id",currentUser.getUserId())
                .set("nickname",updateUserDTO.getNickname())
                .set("avatar",updateUserDTO.getAvatar())
                .set("gender",updateUserDTO.getGender())
                .set("age",updateUserDTO.getAge())
                .set("email",updateUserDTO.getEmail())
                .set("signature",updateUserDTO.getSignature()));
        if(isUpdate){
            return Result.success("更新用户信息成功");
        }
        else {
            return Result.fail(110,"更新用户信息失败");
        }
    }

}
